package sk.stuba.fiit.repka.dp.gui;

import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import sk.stuba.fiit.repka.dp.owl.MyOWLClass;
import sk.stuba.fiit.repka.dp.owl.OWLComponent;
import sk.stuba.fiit.repka.dp.owl.OWLProperty;

public class SelectFromCheckBoxesSP extends JScrollPane {
	
	private List<? extends OWLComponent> components; //input for pane
	
	private Map<JCheckBox, OWLComponent> mapper = new HashMap<JCheckBox, OWLComponent>();// map checkboxes to owlclasses
	
	private List<JCheckBox> checkBoxes = new ArrayList<JCheckBox>();
	
	private JPanel panel;
	
	public SelectFromCheckBoxesSP(List<? extends OWLComponent> classes) {
		this.components = new ArrayList<OWLComponent>(classes); //create list ... changes in new list should not have affect in old list!!!
		
		this.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		this.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		panel = new JPanel();
		this.setViewportView(panel);
		panel.setLayout(new GridLayout(0,2));
		this.generateCheckBox(this.components);
	}
	
	//generate checkboxes from owlclasses and map checkboxes to owlclasses
	private void generateCheckBox(List<? extends OWLComponent> inList) {
		Iterator<? extends OWLComponent> iter = inList.iterator();
		while(iter.hasNext()) {
			OWLComponent o = iter.next();
			JCheckBox chckbxNewCheckBox = new JCheckBox(o.getName());
			this.mapper.put(chckbxNewCheckBox, o); //map checkbox to owlclass
			this.checkBoxes.add(chckbxNewCheckBox); //add checkbox to list
			this.panel.add(chckbxNewCheckBox);
			if(o.hasSubComponent()) {
				this.generateCheckBox(o.getSubComponents());
			}
		}
	}
	
	//return all owlclasses which were selected by user 
	public List<MyOWLClass> getSelectedOWLClassesFromCheckBoxes() {
		List<MyOWLClass> output = new ArrayList<MyOWLClass>();
		Iterator<JCheckBox> iter = this.checkBoxes.iterator();
		while(iter.hasNext()) {
			JCheckBox c = iter.next();
			if(c.isSelected()) {
				output.add((MyOWLClass)this.mapper.remove(c));
			}
		}
		return output;
	}
	
	//return all OWLProperties which were selected by user 
	public List<OWLProperty> getSelectedPropertiesFromCheckBox() {
		List<OWLProperty> output = new ArrayList<OWLProperty>();
		Iterator<JCheckBox> iter = this.checkBoxes.iterator();
		while(iter.hasNext()) {
			JCheckBox c = iter.next();
			if(c.isSelected()) {
				output.add((OWLProperty)this.mapper.remove(c));
			}
		}
		return output;
	}
	
}
